/**
 * @(#)ServletInitialization.java Sep 21, 2009
 *   
 * Copyright  (c) 2009-2010 Wilmar IT Service,  Inc.   
 * All  rights  reserved.   
 * TODO
 */

package com.wilmar.process.web.listeners;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.log4j.Logger;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.wilmar.process.core.ProcessSystemDeclareKeys;
import com.wilmar.process.enumerate.EnumSystemParameterNameSet;
import com.wilmar.process.system.ProcessSystem;

/**
 * @author MaKuBEX Email:makubexnet@gmail.com
 * @version 1.0.0
 */
public class InitializationListener implements ServletContextListener {

	/**
	 * @serialField
	 */
	private static final long serialVersionUID = -1309660157937002918L;

	private static final Logger log = Logger
			.getLogger(InitializationListener.class);

	/**
	 * @see javax.servlet.ServletContextListener#contextDestroyed(javax.servlet.ServletContextEvent)
	 */
	public void contextDestroyed(ServletContextEvent arg0) {
		log.info("System down");
	}

	/**
	 * @see javax.servlet.ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent)
	 */
	public void contextInitialized(ServletContextEvent servletContextEvent) {
		log.info("Starting " + ProcessSystemDeclareKeys.SYSTEM_NAME + "...");
		ProcessSystem.webAppContext = WebApplicationContextUtils
				.getWebApplicationContext(servletContextEvent
						.getServletContext());

		Enumeration<String> param = servletContextEvent.getServletContext()
				.getInitParameterNames();
		Map<EnumSystemParameterNameSet, Object> params = new HashMap<EnumSystemParameterNameSet, Object>();
		while (param.hasMoreElements()) {
			String paramName = param.nextElement();
			try {
				EnumSystemParameterNameSet param_ = EnumSystemParameterNameSet
						.valueOf(paramName);
				params.put(param_, servletContextEvent.getServletContext()
						.getInitParameter(paramName));
			} catch (Exception e) {
				continue;
			}
		}
		ProcessSystem.systemParameters = params;
		log.info(ProcessSystemDeclareKeys.SYSTEM_NAME + " started!");
	}
}
